/**
 * Created by HP on 2017/10/17.
 */
var mongoose = require('mongoose');
//引入数据模型
const DataModel = require('../models/cate.model');


//增删改查
//增加
exports.create = function (req,res,next) {
	const  dataModel = new DataModel(req.body);
	//
	console.log(req.body);
	dataModel.save()
		.then(data=>{
			res.json(data);
		})
	
}
//获取一条
exports.get = function (req,res,next) {
	var id = req.params.id;
	DataModel.findById(id, function (err, data) {
		res.json(data);
	})
}

//修改
exports.update = function (req,res,next) {
	var id = req.params.id;
	DataModel.findByIdAndUpdate(id, {$set:req.body}, {new:false})
		.then(data=>{
			res.json(data)
		})
}

//删除
exports.remove = function (req,res,next) {
	const id = req.params.id;
	var ids = [];
	DataModel.findOne({_id:id},function (err,doc) {
		if(doc){
			ids = [doc._id]; //加上自身
			doc.getChildren().then(function(docs){
				var docs_length = docs.length;
				for(var i=0;i<docs_length;i++){
					ids.push(docs[i]._id);
				}
				
				DataModel.remove({_id : {$in:ids}})
				.then(data=>{
					res.json({"msg":"deletes success","status":200});
				})
				
			});
		}
	})
}
exports.getid = function (req,res,next) {
	const id = req.params.id;
	console.log(id);
	var ids = [];
	DataModel.findOne({_id:id},function (err,doc) {
		if(doc){
			ids = [doc._id]; //加上自身
			doc.getChildren().then(function(docs){
				var docs_length = docs.length;
				for(var i=0;i<docs_length;i++){
					ids.push(docs[i]._id);
				}
				console.log(ids);
				res.json(ids);
			});
		}
	})
}




function reverseTree(data,pid) {
	var result =[];
	var temp;
	var data = JSON.parse(JSON.stringify(data));//将DataModel的object转化为js的object
	
	for(var i in data){
		if(data[i].parentId == pid){
			result.push(data[i]);
			
			temp = reverseTree(data,data[i]._id);
			
			if(temp.length >0){
				data[i].children = temp;
			}
		}
	}
	return result;
}
exports.list = function (req,res,next) {
	const type = req.params.type
	DataModel.find({type:type},function (err,data) {
		var rpTree = reverseTree(data,null);
		res.json(rpTree);
	})
}

